import pymongo
from config.config import TEST_PORT,TEST_DB_HOST


class MongoDbLink:
    def __init__(self,host,port,db_name):
        self.host = host
        self.port = port
        self.db_name = db_name
        self.client_link = pymongo.MongoClient(host=self.host,port=self.port)
        self.db_link = self.client_link[self.db_name]

    def insert_one(self,doc,data):
        db_col = self.db_link[doc]
        db_col.insert_one(data)

    def insert_many(self,doc,datas):
        db_col = self.db_link[doc]
        db_col.insert_many(datas)

    def update_one(self,doc,cond,update):
        db_col = self.db_link[doc]
        db_col.update_one(cond,update)

    def update_many(self,doc,cond,update):
        db_col = self.db_link[doc]
        db_col.update_many(cond, update)

    def delete_one(self,doc,cond):
        db_col = self.db_link[doc]
        db_col.delete_one(cond)

    def delete_many(self,doc,cond):
        db_col = self.db_link[doc]
        db_col.delete_many(cond)

    def delete_all(self,doc):
        db_col = self.db_link[doc]
        db_col.delete_many({})

    def find(self,doc,cond):
        db_col = self.db_link[doc]
        li = []
        for i in db_col.find(cond):
            li.append(i)
        return li

    def find_limit(self,doc,cond,limit_no=100,skip_no=0):
        db_col = self.db_link[doc]
        li = []
        for i in db_col.find(cond).limit(limit_no).skip(skip_no):
            li.append(i)
        return li

    def insert(self,doc,data):
        db_col = self.db_link[doc]
        db_col.insert_many(data)

    def count_documents(self,doc,cond):
        db_col = self.db_link[doc]
        return db_col.count_documents(cond)

    def close(self):
        self.client_link.close()


    def aggregate(self,doc,pipeline):
        db_col = self.db_link[doc]
        return db_col.aggregate(pipeline)

